package controller;

import java.awt.event.*;
import javax.swing.JOptionPane;
import model.GameClient;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.io.*;

public class QueueListener implements ActionListener
{
	private GameClient gameClient;

	public QueueListener(GameClient gameClient)
	{
		super();
		this.gameClient = gameClient;
	}

	public void actionPerformed(ActionEvent e) 
	{
		if (gameClient.checkConnected() == true){
			queueGame();
		} else {
			JOptionPane.showMessageDialog(gameClient.getContentPane(), "Please connect to the server\n" +
					"before queueing for a game.","Not Connected",JOptionPane.ERROR_MESSAGE);
		}	
	}

	public void queueGame(){
		try{
			// Scenario 1
			// Send 6 to the server to let it know that we wish to wait for a game

			gameClient.getOutputToServer().write(6);
			gameClient.getOutputToServer().flush();

			// Scenario 2
			// Get input from the Server side, reads the int that is returned
			int queue = gameClient.getInputFromServer().read();

			// Scenario 3
			// 1 from the server means SUCCESS! Proceed to queue for a game. 
			// Otherwise means fail and inform Game Creator Client of error
			if (queue == 1)
			{
				// SERVER WILL PUT US IN A GAME NOW
				// here is where we wait start a new game
				System.out.println("We wait");
				// by choosing a side


				if(gameClient.getInputFromServer().ready()){
					gameClient.chooseSide();

				}


				//gameClient.chooseSide();

				// Server will create a monster once all clients have chosen a side
				// After a monster has been created, wait a few seconds then start game

				// if (server responds with a number){
				// gameClient.startGame();
				// }
			}
			else if (queue == 2){
				System.out.println("Player please wait for new queue");

//				if(gameClient.getInputFromServer().ready() == true){
//					if(gameClient.getInputFromServer().read() == 1)
//						gameClient.chooseSide();
//
//				}
				
				ClientListener cL = new ClientListener(gameClient.getOutputToServer(), gameClient.getInputFromServer(), gameClient);
				
		        cL.start();
			}
			else{
				JOptionPane.showMessageDialog(gameClient.getContentPane(), "Cannot add you to a queue...\nPlease " +
						"try queueing again later","Queue Game Error",JOptionPane.ERROR_MESSAGE);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
